//
//  ApplyInfoDetailViewController.m
//  Jyxt
//
//  Created by 王炜光 on 2017/8/18.
//  Copyright © 2017年 DaLian Rental Housing Management. All rights reserved.
//

#import "ApplyInfoDetailViewController.h"
#import "ResidencePermitViewModel.h"
#import "UserCenterViewModel.h"
#import "RefuseResidencePermitViewController.h"
#import <LemonBubble.h>
#import <YYKit.h>
#import "ContractReviewViewController.h"





#import "NetTool.h"
@interface ApplyInfoDetailViewController ()<UIScrollViewDelegate>

@property (nonatomic ,strong) NSDictionary *contractDetailDic;

/**
 滑动载体
 */
@property (nonatomic, strong)UITableView *bgTableView;

@property (nonatomic, strong)UIScrollView *imageScrollView;

@property (nonatomic, strong)UIButton *upBtn;

@property (nonatomic, strong)UIButton *nextBtn;

@property (nonatomic, strong)UIView *nextOrUpBGView;

@property (nonatomic, strong)UIView *btnBGView;

@property (nonatomic, strong)NSMutableArray *imageArr;

@property (nonatomic, strong)UIView *headerView;

@property (nonatomic, strong)UIButton *refuseBtn;
@property (nonatomic, strong)UIButton *adoptBtn;

@property (nonatomic, strong)NSString *url;
@end

@implementation ApplyInfoDetailViewController

- (void)initView{
    self.view.backgroundColor = LKColorMake(245, 245, 245, 1);
    CGFloat bgViewHeight;
    if (self.isWaiting) {
        bgViewHeight = 134;
    }else{
        bgViewHeight = 60;
    }
    
    _bgTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-60) style:UITableViewStylePlain];
    _bgTableView.tableHeaderView = [self createHeaderView];
    _bgTableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:_bgTableView];
    
    _btnBGView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-70, SCREEN_WIDTH, 70)];
    _btnBGView.backgroundColor = self.view.backgroundColor;
    [self.view addSubview:_btnBGView];
    
    _refuseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _refuseBtn.frame = CGRectMake(15, 15, (SCREEN_WIDTH-45)/2, 40);
    [_refuseBtn setTitle:@"拒绝申请" forState:UIControlStateNormal];
    [_refuseBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_refuseBtn setBackgroundColor:[UIColor redColor]];
    _refuseBtn.layer.cornerRadius = 5;
    [_refuseBtn addTarget:self action:@selector(refuseBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [_btnBGView addSubview:_refuseBtn];
    
    _adoptBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _adoptBtn.frame = CGRectMake(30+(SCREEN_WIDTH-45)/2, 15, (SCREEN_WIDTH-45)/2, 40);
    [_adoptBtn setTitle:@"通过申请" forState:UIControlStateNormal];
    [_adoptBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_adoptBtn setBackgroundColor:LKColorMake(100,131,228, 1)];
    _adoptBtn.layer.cornerRadius = 5;
    [_adoptBtn addTarget:self action:@selector(adoptBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [_btnBGView addSubview:_adoptBtn];
    
    
    _nextOrUpBGView = [[UIView alloc]initWithFrame:_btnBGView.frame];
    _nextOrUpBGView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:_nextOrUpBGView];
    
    _upBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _upBtn.frame = CGRectMake(15, 15, 70, 40);
    [_upBtn setTitle:@"上一张" forState:UIControlStateNormal];
    [_upBtn addTarget:self action:@selector(upImageAction:) forControlEvents:UIControlEventTouchUpInside];
    [_nextOrUpBGView addSubview:_upBtn];
    
    _nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _nextBtn.frame = CGRectMake(SCREEN_WIDTH - 85, 15, 70, 40);
    [_nextBtn setTitle:@"下一张" forState:UIControlStateNormal];
    [_nextBtn addTarget:self action:@selector(nextImageAction:) forControlEvents:UIControlEventTouchUpInside];
    [_nextOrUpBGView addSubview:_nextBtn];
    
    
    
    [self.view sendSubviewToBack:_nextOrUpBGView];
}

- (void)upImageAction:(UIButton *)btn{
    [_imageScrollView setContentOffset:CGPointMake(_imageScrollView.contentOffset.x-SCREEN_WIDTH, 0) animated:YES];
    if (_imageScrollView.contentOffset.x == SCREEN_WIDTH) {
        btn.alpha = 0.5;
        btn.enabled = NO;
    }else{
        btn.alpha = 1;
        btn.enabled = YES;
    }
    _nextBtn.alpha = 1;
    _nextBtn.enabled = YES;
}
- (void)nextImageAction:(UIButton *)btn{
    [_imageScrollView setContentOffset:CGPointMake(_imageScrollView.contentOffset.x+SCREEN_WIDTH, 0) animated:YES];
    if (_imageScrollView.contentOffset.x == SCREEN_WIDTH*(_imageArr.count-1)) {
        btn.alpha = 0.5;
        btn.enabled = NO;
    }else{
        btn.alpha = 1;
        btn.enabled = YES;
    }
    _upBtn.alpha = 1;
    _upBtn.enabled = YES;
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (scrollView.tag < 4000) {
        _upBtn.enabled = NO;
        _nextBtn.enabled = NO;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
//    if (scrollView.contentOffset.x == 0) {
//        _upBtn.enabled = NO;
//        _upBtn.alpha = 0.5;
//        _nextBtn.alpha = 1;
//        _nextBtn.enabled = YES;
//    }else if (scrollView.contentOffset.x == SCREEN_WIDTH*(_imageArr.count-1)) {
//        _nextBtn.enabled = NO;
//        _nextBtn.alpha = 0.5;
//        _upBtn.alpha = 1;
//        _upBtn.enabled = YES;
//    }else{
//        _upBtn.alpha = 1;
//        _upBtn.enabled = YES;
//        _nextBtn.alpha = 1;
//        _nextBtn.enabled = YES;
//    }
//     NSLog(@"12311");
}
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    
    if (scrollView.tag < 4000) {
        NSLog(@"123");
        if (scrollView.contentOffset.x == 0) {
            _upBtn.enabled = NO;
            _upBtn.alpha = 0.5;
            _nextBtn.alpha = 1;
            _nextBtn.enabled = YES;
        }else if (scrollView.contentOffset.x == SCREEN_WIDTH*(_imageArr.count-1)) {
            _nextBtn.enabled = NO;
            _nextBtn.alpha = 0.5;
            _upBtn.alpha = 1;
            _upBtn.enabled = YES;
        }else{
            _upBtn.alpha = 1;
            _upBtn.enabled = YES;
            _nextBtn.alpha = 1;
            _nextBtn.enabled = YES;
        }
        
    }
}

- (void)createImageScrollView{
    
    _imageScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _imageScrollView.pagingEnabled = YES;
    _imageScrollView.bounces = NO;
    _imageScrollView.scrollEnabled = NO;
    _imageScrollView.delegate = self;
    _imageScrollView.contentSize = CGSizeMake(SCREEN_WIDTH *_imageArr.count, SCREEN_HEIGHT-20);
    [self.view addSubview:_imageScrollView];
    
    
    UIView *blackView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH*_imageArr.count, SCREEN_HEIGHT)];
    blackView.backgroundColor = [UIColor blackColor];
    blackView.alpha = 0.5;
    blackView.userInteractionEnabled = NO;
    blackView.onTap = ^(UIView *view){
        [self.view sendSubviewToBack:_imageScrollView];
        [self.view sendSubviewToBack:_nextOrUpBGView];
    };
    [_imageScrollView addSubview:blackView];
    for (NSInteger i = 0; i < _imageArr.count; i++) {
        UIScrollView *bsScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(i *SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT-70)];
        //设置scrollview的代理人
        bsScrollView.delegate = self;
        bsScrollView.tag = 4000 + i;
        //设置缩放的最大比例
        bsScrollView.maximumZoomScale = 2;
        bsScrollView.onTap = ^(UIView *view){
            [self.view sendSubviewToBack:_imageScrollView];
            [self.view sendSubviewToBack:_nextOrUpBGView];
        };
        //设置缩放的比例
        bsScrollView.zoomScale = 0.5;
        UIImageView *tempView = [[UIImageView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT/2-SCREEN_WIDTH/4*3/2-35, SCREEN_WIDTH, SCREEN_WIDTH/4*3)];
        tempView.tag = 5000+i;
        tempView.image = [UIImage imageNamed:@"rp_loading_image"];
        NSString *imgURL =((NSString *)_imageArr[i][@"id"]).length > 0?_imageArr[i][@"id"]:@"";
        [ResidencePermitViewModel getResidencePermitApplyImageWithData:@{@"id":imgURL} success:^(id response) {
            
            if (response) {
                
                tempView.image = response;
            }else{
                tempView.image = [UIImage imageNamed:@"rp_unload_image"];
            }
            tempView.onTap = ^(UIView *v){
                [self.view sendSubviewToBack:_imageScrollView];
                [self.view sendSubviewToBack:_nextOrUpBGView];
            };
            
        } failed:^(NSString *reason) {
            tempView.image = [UIImage imageNamed:@"rp_unload_image"];
//            [self showErrorWithTitle:[NSString stringWithFormat:@"%@图片获取失败",_imageArr[i][@"fileName"]] autoCloseTime:1];
        }];
        [bsScrollView addSubview:tempView];
        [_imageScrollView addSubview:bsScrollView];
    }
    
    [self.view sendSubviewToBack:_imageScrollView];
    
}
-(void)scrollViewDidZoom:(UIScrollView *)scrollView{
    if (scrollView.tag >= 4000) {
        
        UIImageView *image = (UIImageView *)[self.view viewWithTag:scrollView.tag+1000];
        image.center = CGPointMake(scrollView.contentSize.width/2, scrollView.frame.size.height/2) ;
    }
}
//可以放大与缩小的协议
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    
    UIImageView *image = (UIImageView *)[self.view viewWithTag:scrollView.tag+1000];
    return image;
}

- (UIView *)createHeaderView{
    _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 875)];
    
    
    NSArray *titleArr = @[@"申请人",@"身份证号",@"居住类型",@"申请条件",@"居住地址",@"申请状态",@"所属行政区",@"所属派出所",@"房屋租赁合同"];
    for (NSInteger i = 0 ; i < titleArr.count; i++) {
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 48*i, 80, 48)];
        titleLabel.tag = 1000+i;
        titleLabel.text = titleArr[i];
        titleLabel.font = [UIFont systemFontOfSize:13];
        titleLabel.textColor = LKColorMake(155, 155, 155, 1);
        [_headerView addSubview:titleLabel];
        
        UILabel *valueLabel = [[UILabel alloc]initWithFrame:CGRectMake(110, 48*i, SCREEN_WIDTH-125, 48)];
        valueLabel.tag = 2000+i;
        valueLabel.numberOfLines = 0;
        valueLabel.font = [UIFont systemFontOfSize:13];
        [_headerView addSubview:valueLabel];
        
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(15, 48+48*i, SCREEN_WIDTH-15, 0.6)];
        lineView.backgroundColor = LKColorMake(200, 200, 200, 1);
        [_headerView addSubview:lineView];
        
        if (i == titleArr.count-1) {
            UIImageView *arrowImageView = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-35, 48*i+14+10, 20, 20)];
            arrowImageView.image = [UIImage imageNamed:@"m_common_indicator"];
            [_headerView addSubview:arrowImageView];
            
            valueLabel.frame = CGRectMake(110, 48*i+10, SCREEN_WIDTH-145, 48);
            valueLabel.textAlignment = NSTextAlignmentRight;
            
            UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(0,48*i , SCREEN_WIDTH, 10)];
            view1.backgroundColor = LKColorMake(245, 245, 245, 1);
            [_headerView addSubview:view1];
            
            UIView *view2 = [[UIView alloc]initWithFrame:CGRectMake(0,48*i+48+10 , SCREEN_WIDTH, 10)];
            view2.backgroundColor = LKColorMake(245, 245, 245, 1);
            [_headerView addSubview:view2];
            
            titleLabel.frame = CGRectMake(15, 48*i+10, 80, 48);
            lineView.hidden = YES;
            
            titleLabel.onTap = ^(UIView *v){
                if (self.url.length > 0) {
//                    NSString *appendURL = [NSString stringWithFormat:@"%@?%@",HTML_INFOSEARCH_CONTRACT_DETAIL,self.url];
                    
//                    NSLog(@"%@",appendURL);
//                    MIX_OPEN(appendURL);
                    ContractReviewViewController *tempVC = [[ContractReviewViewController alloc]init];
                    tempVC.contractID = self.contractDetailDic[@"cid"];
                    [LKFreeCtrl pushViewController:tempVC];
                }else{
                    [self showErrorWithTitle:@"无有效合同" autoCloseTime:2];
                }
            };
            valueLabel.onTap = ^(UIView *v){
                if (self.url.length > 0) {
                    ContractReviewViewController *tempVC = [[ContractReviewViewController alloc]init];
                    tempVC.contractID = self.contractDetailDic[@"cid"];
                    [LKFreeCtrl pushViewController:tempVC];
//                    NSString *appendURL = [NSString stringWithFormat:@"%@?%@",HTML_INFOSEARCH_CONTRACT_DETAIL,self.url];
//                    NSLog(@"%@",appendURL);
//                    MIX_OPEN(appendURL);
                }else{
                    [self showErrorWithTitle:@"无有效合同" autoCloseTime:2];
                }
            };
        }
    }
    
    UILabel *lastTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 48*titleArr.count+20, 70, 48)];
    lastTitleLabel.textColor = LKColorMake(155, 155, 155, 1);
    lastTitleLabel.text = @"申请材料";
    lastTitleLabel.font = [UIFont systemFontOfSize:13];
    [_headerView addSubview:lastTitleLabel];
    return _headerView;
    
}

- (void)createImageView{
    NSArray *imageTitleArr = @[@"身份证正面照片",@"身份证背面照片",@"申请材料照片"];
    
    for (NSInteger i = 0; i < _imageArr.count; i++) {
        UIImageView *tempImageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 48*9+15 +160 * i + 20, 150, 120)];
        tempImageView.tag = 3000 + i;
        tempImageView.image = [UIImage imageNamed:@"rp_loading_image"];
        tempImageView.onTap = ^(UIView *view){
            [_imageScrollView setContentOffset:CGPointMake((tempImageView.tag - 3000)*SCREEN_WIDTH, 0)];
            [self.view bringSubviewToFront:_imageScrollView];
            [self.view bringSubviewToFront:_nextOrUpBGView];
            _upBtn.enabled = YES;
            _upBtn.alpha = 1;
            _nextBtn.enabled = YES;
            _nextBtn.alpha = 1;
            if (tempImageView.tag == 3000) {
                _upBtn.enabled = NO;
                _upBtn.alpha = 0.5;
            }
            if (tempImageView.tag == 3000+_imageArr.count-1) {
                _nextBtn.enabled = NO;
                _nextBtn.alpha = 0.5;
            }
        };
        [_headerView addSubview:tempImageView];
        
        UILabel *detailLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 48*9+15+120+160 * i + 20, 150, 25)];
        detailLabel.font = [UIFont systemFontOfSize:13];
        detailLabel.textAlignment = NSTextAlignmentCenter;
        if (i<3) {
            
            detailLabel.text = imageTitleArr[i];
        }else{
            detailLabel.text = imageTitleArr[2];
        }
        [_headerView addSubview:detailLabel];
        NSString *imgURL =((NSString *)_imageArr[i][@"id"]).length > 0?_imageArr[i][@"id"]:@"";
        [ResidencePermitViewModel getResidencePermitApplyImageWithData:@{@"id":imgURL} success:^(id response) {
            if (response) {
                tempImageView.image = response;
                
            }else{
                tempImageView.image = [UIImage imageNamed:@"rp_unload_image"];
            }
        } failed:^(NSString *reason) {
            tempImageView.image = [UIImage imageNamed:@"rp_unload_image"];
//            [self showErrorWithTitle:@"图片获取失败" autoCloseTime:1];
        }];
    }
    
    _headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 48*9+15+160*_imageArr.count + 20);
}

- (void)refuseBtnAction:(UIButton *)btn{
    RefuseResidencePermitViewController *tempVC = [[RefuseResidencePermitViewController alloc]init];
    tempVC.valueDic = self.valueDic;
    [LKFreeCtrl pushViewController:tempVC];
}

- (void)adoptBtnAction:(UIButton *)btn{
    [self showRoundProgressWithTitle:@"加载中..."];
    [ResidencePermitViewModel postResidencePermitApplyWithData:@{@"utoken":[UserCenterViewModel getLocalUToken],@"id":self.valueDic[@"id"]} success:^(id response) {
        [self hideBubble];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"审核完成，您已通过此条居住证办理申请，可在“已通过”中查看。" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popToRootViewControllerAnimated:YES];
            
        }];
        [alert addAction:sureAction];
        [self presentViewController:alert animated:YES completion:nil];
        
    } failed:^(NSString *reason) {
        
        [self showErrorWithTitle:reason autoCloseTime:3];
    }];
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.title = @"申请信息详情";
    if (!_imageScrollView) {
        [self showRoundProgressWithTitle:@"加载中..."];
        NSString *idStr = ((NSString *)self.valueDic[@"id"]).length > 0 ? self.valueDic[@"id"]:@"";
        [ResidencePermitViewModel getResidencePermitDetailWithData:@{@"utoken":[UserCenterViewModel getLocalUToken],@"id":idStr} success:^(id response) {
            self.contractDetailDic = response[@"data"];
            NSLog(@"TTTTTTOOOOOKKKKEEEEENNNN  %@",[UserCenterViewModel getLocalUToken]);
            [[NSUserDefaults standardUserDefaults] setObject:self.contractDetailDic forKey:@"CONTRACTDETAILCID"];
            NSArray *valueArr = @[self.contractDetailDic[@"name"],self.contractDetailDic[@"idNo"],self.contractDetailDic[@"dwellingTypeName"],self.contractDetailDic[@"applicationConditionsName"],self.contractDetailDic[@"houseAddr"],self.contractDetailDic[@"applicationStatusName"],self.contractDetailDic[@"areaName"],self.contractDetailDic[@"pcsName"],@"查看详情"];
            if (![self.contractDetailDic[@"cid"] isKindOfClass:[NSNull class]]) {
                self.url = self.contractDetailDic[@"cid"];
            }
            for (NSInteger i = 0 ; i < valueArr.count; i++) {
                UILabel *valueLabel = [self.view viewWithTag:2000+i];
                valueLabel.text = valueArr[i];
            }
            [self showRightWithTitle:@"加载成功" autoCloseTime:2];
            
            CGFloat bgViewHeight;
            if ([valueArr[5] isEqualToString:@"待审核"] && [self.contractDetailDic[@"priviledge"] boolValue]) {
                _btnBGView.hidden = NO;
                bgViewHeight = 134;
            }else{
                _btnBGView.hidden = YES;
                bgViewHeight = 60;
            }
            
            _bgTableView.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-bgViewHeight);
            _imageArr = [[NSMutableArray alloc]init];
            
            for (NSDictionary *tempDic in self.contractDetailDic[@"materials"]) {
                if ([tempDic[@"fileType"]isEqualToString:@"35"]) {
                    [_imageArr insertObject:tempDic atIndex:0];
                }else if ([tempDic[@"fileType"]isEqualToString:@"36"]) {
                    if (_imageArr.count > 0) {
                        [_imageArr insertObject:tempDic atIndex:1];
                    }else{
                        [_imageArr insertObject:tempDic atIndex:0];
                    }
                }else{
                    
                    [_imageArr addObject:tempDic];
                }
            }
            [self createImageView];
            [self createImageScrollView];
            
            [self.bgTableView reloadData];
            
        } failed:^(NSString *reason) {
            [self showErrorWithTitle: reason autoCloseTime: 3];
            
        }];
        _btnBGView.hidden = YES;
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)lkIsUserFullscreenBackGesture{
    return NO;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
